import org.dom4j.*;
import org.dom4j.io.SAXReader;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.util.Iterator;
import java.util.List;

public class TestDomJ {
    public static void main(String[] args) throws DocumentException {
        //System.out.println("Hello dom4j!");
        TestDomJ test = new TestDomJ();
        String filepath = "src/main/java/class.xml";
        File file = new File(filepath);

        try {
            Document document=test.parse(file);
//            System.out.println(document);
            test.handle(document);
            //创建xml文件
            Document document1=test.createDocument();
            test.createXml(document1);
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }
    //获取domj的文档对象
    public Document parse(File file) throws DocumentException {
        SAXReader reader = new SAXReader();
        Document document = reader.read(file);
        return document;
    }
    public void handle(Document document){
        System.out.println("handle"+document);
        //获取节点列表
        //List<Node> list=document.selectNodes("//age");
        //list.forEach(node -> System.out.println(node.getName()+":"+node.getText()));
        //获取指定节点
        //List<Node> list=document.selectNodes("/students/stu/*");
        //list.forEach(node -> System.out.println(node.getName()+":"+node.getText()));
        //获取所有节点
        Element root=document.getRootElement();
        for (Iterator<Element> it = root.elementIterator(); it.hasNext();){
            Element element=it.next();
            System.out.println("name:"+element.getName());
        }
        //获取根节点下的指定名称的儿子节点
        for (Iterator<Element> it = root.elementIterator("stu"); it.hasNext();){
            Element element=it.next();
            System.out.println("name:"+element.getName());
        }
        //获取根节点的属性
        for (Iterator<Attribute> it = root.attributeIterator(); it.hasNext();){
            Attribute attribute=it.next();
            System.out.println("name:"+attribute.getName());
            System.out.println("value:"+attribute.getValue());
        }
    }
    //创建xml文件
    //创建document对象
    public Document createDocument(){
        Document document= DocumentHelper.createDocument();
        Element root=document.addElement("root");
        Element stu=root.addElement("stu").addAttribute("id","1").addAttribute("gender","0");
        stu.addElement("name").addText("zhangsan");
        stu.addElement("age").addText("18");
        return document;
    }
    public void createXml(Document document){
        try {
            //创建XML文件
            FileWriter fileWriter=new FileWriter("src/main/java/root.xml");
            //写入文件
            document.write(fileWriter);
            //关闭流
            fileWriter.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
